package com.zz.extension.controller;

import com.zz.extension.constant.Constants;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/producer")
public class ProducerController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource(name = "transRabbitTemplate")
    private RabbitTemplate transRabbitTemplate;

    // 消息确认
    @RequestMapping("/Ack")
    public String ack(){
        rabbitTemplate.convertAndSend("ack.exchange", "ack", "消息确认");
        return "消息发送成功";
    }
    // TTL
    @RequestMapping("/TTL")
    public String ttl(){
        rabbitTemplate.convertAndSend(Constants.TTL_EXCHANGE, "ttl", "消息确认", message -> {
            message.getMessageProperties().setExpiration("10000");
            return message;
        });
        System.out.println("消息发送成功");
        return "消息发送成功";
    }
    @RequestMapping("/TTL2")
    public String ttl2(){
        rabbitTemplate.convertAndSend(Constants.TTL_EXCHANGE, "ttl", "消息确认");
        System.out.println("消息发送成功");
        return "消息发送成功";
    }

    // 死信队列
    @RequestMapping("/DLX")
    public String dlx(){
        rabbitTemplate.convertAndSend(Constants.NORMAL_EXCHANGE, "normal", "消息确认");
        System.out.println("消息发送成功");
        return "消息发送成功";
    }

    // 延迟队列
    @RequestMapping("/Delay")
    public String delay(){
        rabbitTemplate.convertAndSend(Constants.DELAY_EXCHANGE, "delay", "消息确认", message -> {
            message.getMessageProperties().setDelay(20000);
            return message;
        });

        rabbitTemplate.convertAndSend(Constants.DELAY_EXCHANGE, "delay", "消息确认", message -> {
            message.getMessageProperties().setDelay(10000);
            return message;
        });
        System.out.println("消息发送成功" + new Date());
        return "消息发送成功";

    }

    // 事务
    @RequestMapping("/Trans")
    public String trans(){
        transRabbitTemplate.convertAndSend("",Constants.TRANS_QUEUE, "trans test1");
        int num = 3/0;
        transRabbitTemplate.convertAndSend("",Constants.TRANS_QUEUE, "trans test2 ");
        System.out.println("消息发送成功");
        return "消息发送成功";
    }
}
